﻿using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using SymbolicLinkManageCore;
using SymbolicLinkManageUI.Lib;
using SymbolicLinkManageUI.Library;

namespace SymbolicLinkManageUI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainWindowVM mainWindowVM;
        public MainWindow()
        {
            ManageCore.MainWindow = this;
            ManageCore.LogManage = LogManage.Instance;
            InitializeComponent();
            Title = ProcessSingleControl.MainWindowTitle;
            mainWindowVM = new MainWindowVM(this);
            DataContext = mainWindowVM;
            Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ((HwndSource)PresentationSource.FromVisual(this)).AddHook(WndProc);
            if (string.IsNullOrWhiteSpace(Program.Args) || PathInfo.GetPathType(Program.Args) == PathType.NotExistType)
                return;
            Task.Run(() => 
            {
                Task.Delay(1500);
                this.Dispatcher.BeginInvoke(() => { SetWindow(Program.Args); });
            });
            //this.SourceInitialized += MainWindow_SourceInitialized;
        }

        //private void MainWindow_SourceInitialized(object? sender, EventArgs e)
        //{
        //    IntPtr hwnd = new WindowInteropHelper(this).Handle;
        //    HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(WndProc));
        //}

        //protected override void OnSourceInitialized(EventArgs e)
        //{
        //    base.OnSourceInitialized(e);
        //    ((HwndSource)PresentationSource.FromVisual(this)).AddHook(myHook);

        //    //HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
        //    //source.AddHook(new HwndSourceHook(myHook));
        //}

        private nint WndProc(nint hwnd, int msg, nint wParam, nint lParam, ref bool handled)
        {
            if (msg == ProcessSingleControl.WM_COPYDATA)
            {
                object? h = System.Runtime.InteropServices.Marshal.PtrToStructure(lParam, typeof(CopyDataStruct));
                if (h == null)
                    return nint.Zero;
                CopyDataStruct cds = (CopyDataStruct)h;
                string arg = cds.lpData;
                this.Dispatcher.BeginInvoke(() => { SetWindow(arg); });
                handled = true;
            }
            return nint.Zero;
        }

        private void SetWindow(string args)
        {
            this.Activate();
            mainWindowVM.SetArg(args);
        }
    }
}